<?php

namespace App\Models\Base;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends BaseModel
{
    use SoftDeletes;

    protected $table = 'bas_order';

    protected $primaryKey = 'order_id';

    /* 订单状态 未支付 */
    const ORDER_STATUS_WAIT = 1;

    /* 订单状态 已支付 */
    const ORDER_STATUS_OK = 2;

    /* 订单状态 已退款 */
    const ORDER_STATUS_REFUND = 3;

    /* 订单状态 支付失败 */
    const ORDER_STATUS_FAIL = 4;

    /* 支付方式 账户余额 */
    const PAY_METHOD_ACCOUNT = 1;

    /* 支付方式 微信支付 */
    const PAY_METHOD_WECHAT = 2;

    /* 支付方式 支付宝支付 */
    const PAY_METHOD_ALYPAY = 3;
    /**
     * 生成唯一订单号
     * @return bool|string
     */
    public static function createdUniqueOrderNumber()
    {
        $orderNum = substr(date('YmdHis', time()) . mt_rand(10000, time()), 0, 20);

        $orderInfo = self::where([
            'order_number' => $orderNum
        ])->first();

        if ($orderInfo) self::createdUniqueOrderNumber();

        return $orderNum;
    }

    /**
     * 创建订单
     * @param $data
     * @return bool
     */
    public static function createOrder($data)
    {
        $order = new self();
        $order->order_price = $data['order_price'];
        $order->user_id = $data['user_id'];
        $order->pay_method = $data['pay_method'];
        $order->order_number = self::createdUniqueOrderNumber();
        $order->created_at = date('Y-m-d H:i:s');
        if (!$order->save()) return false;

        return $order;
    }
}